package com.unswift.utils;

import java.io.File;
import java.io.StringWriter;

import com.unswift.QuickApplication;
import com.unswift.window.factory.MessageFactory;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * freemark 公共操作类
 * @author unswift
 *
 */
public final class FreemarkerUtils {

	private static Configuration configuration;
	
	/**
	 * 加载freemarker模板配置
	 * @return
	 */
	public static void setConfiguration(String basePath){
		try {
			configuration=new Configuration(Configuration.VERSION_2_3_0);
			configuration.setTemplateLoader(new FileTemplateLoader(new File(basePath)));
			configuration.setSettings(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));
		} catch (Exception e) {
			e.printStackTrace();
			MessageFactory.error(QuickApplication.getWindow(), "freemarker模板加载异常，消息："+e.getMessage());
		}
	}
	
	/**
	 * 解析指定路径的模板文件
	 * @param fileName
	 * @param model
	 * @return
	 */
	public static String getTemplate(String ftlFile, Object model){
		try {
			Template template=configuration.getTemplate(ftlFile, "UTF-8");
			StringWriter writer=new StringWriter();
			template.process(model, writer);
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
